package login;

import JavaBean.User;

import javax.persistence.EntityManager;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sai
 * Created by Sai on 2019-03-03.
 */
@SuppressWarnings("Duplicates")
@WebServlet(urlPatterns = {"/login/dgut"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        int flag=0;
        LoginController loginController=new LoginController();
        Map<String,String> userinfo = new HashMap<String,String>();
        userinfo = loginController.login(request,response);
        String username = userinfo.get("username");
        String name = userinfo.get("name");

        try {
            Connection connection = (Connection) getServletContext().getAttribute("connection");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from USER");
            while(resultSet.next()){
                if(resultSet.getString("SNO").equals(username)){
                    User user= new User(resultSet.getString("NAME"),resultSet.getString("EMAIL"),resultSet.getString("PASSWORD"),resultSet.getString("IMG"),resultSet.getString("SNO"));
                    request.getSession().setAttribute("user",user);
                    flag=1;
                }
            }
            if(flag==0) {
                String Email ="test@qq.com";
                String img = "picture/"+username+".jpg";
                EntityManager em = (EntityManager)request.getAttribute("_entity.manager");
                User userr = new User( name, Email,"123456",img,username);
                em.persist(userr);
                request.getSession().setAttribute("user",userr);
            }
            response.sendRedirect("/UserPage.jsp");
        }
        catch(SQLException e){
            response.sendRedirect("/error.jsp");
            e.getErrorCode();
        }
    }
}
